package com.pdd.message.server.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pdd.commons.entity.dao.Blog_Message;
import com.pdd.commons.entity.dao.Blog_Message_List;
import com.pdd.commons.entity.dto.SendMessageFrom;
import com.pdd.commons.entity.vo.AccountInfo_Vo;
import com.pdd.commons.entity.vo.Message_User_Vo;
import com.pdd.commons.entity.vo.Message_Vo;
import com.pdd.commons.response.ResponseEntity;
import com.pdd.commons.utils.AccountUtil;
import com.pdd.commons.utils.RedisUtils;
import com.pdd.message.enums.WebResultEmun;
import com.pdd.message.response.ResponseResult;
import com.pdd.message.server.commons.consts.TCPServerConst;
import com.pdd.message.server.commons.utils.SystemMessageUtil;
import com.pdd.message.server.mapper.Blog_MessageMapper;
import com.pdd.message.server.mapper.Blog_Message_ListMapper;
import com.pdd.message.server.service.Blog_MessageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * @author:liyangpeng
 * @date:2019/7/30 15:00
 */
@Service
@Slf4j
public class Blog_MessageServiceImpl implements Blog_MessageService {

    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private AccountUtil accountUtil;
    @Autowired
    private Blog_MessageMapper blog_messageMapper;
    @Autowired
    private Blog_Message_ListMapper blog_message_listMapper;
    /**
     * 查询可用的TCP推送服务列表
     * @return
     */
    @Override
    public ResponseEntity getTcpServerList() {
        Long size=redisUtils.listSize(TCPServerConst.SERVER_ID);
        if(size==null||size<1){
            log.debug("【pdd博客】未找到可用的消息推送TCP连接");
            return ResponseResult.Return(WebResultEmun.TCP_SERVER_LIST_EMPTY_ERROR);
        }
        List<String> serverList=redisUtils.listRangeList(TCPServerConst.SERVER_ID,0L,size);
        return ResponseResult.Return(serverList);
    }

    /**
     * 发送私聊消息
     * @param sendMessageFrom
     * @return
     */
    @Override
    public ResponseEntity sendMessage(SendMessageFrom sendMessageFrom) {

        AccountInfo_Vo accountInfo_vo=accountUtil.getLoginInfo();

        if(accountInfo_vo==null){
            return ResponseResult.Return(WebResultEmun.LOGIN_INFO_NOT_EXISTS);
        }

        //自己不能给自己发送消息
        if(accountInfo_vo.getId().equals(sendMessageFrom.getAuthor_id())){
            return ResponseResult.Return(WebResultEmun.SEND_MESSAGE_ERROR);
        }
        //消息不能是空格
        if(sendMessageFrom.getContent().replaceAll("\\s+","").isEmpty()){
            return ResponseResult.Return(WebResultEmun.MESSAGE_CONTENT_EMPTY_ERROR);
        }
        //消息发送者
        Message_User_Vo message_user_vo=new Message_User_Vo();
        BeanUtils.copyProperties(accountInfo_vo,message_user_vo);

        //消息主体
        Message_Vo message_vo=new Message_Vo().setUser_vo(message_user_vo).setTimeStamp(new Date());
        BeanUtils.copyProperties(sendMessageFrom,message_vo);

        //mysql保存聊天记录
        new Blog_Message()
                .setMsg_author_id(accountInfo_vo.getId())
                .setMsg_author_id_s(sendMessageFrom.getAuthor_id())
                .setContent(message_vo.getContent())
                .setMsg_type(sendMessageFrom.getMsg_type()).setPublishTime(message_vo.getTimeStamp()).insert();

        //在对方的聊天列表新增一条数据
        Blog_Message_List blog_message_list=blog_message_listMapper.selectOne(Wrappers.<Blog_Message_List>query().
                eq("msg_author_id",sendMessageFrom.getAuthor_id()).eq("msg_author_id_s",accountInfo_vo.getId()).eq("isdel",0));
        if(blog_message_list!=null){
            //更新未读数量
            blog_message_list.setUnread(blog_message_list.getUnread()+1);
            blog_message_list.updateById();
        }else{
            //新增聊天列表记录未读数
            new Blog_Message_List()
                    .setMsg_author_id(sendMessageFrom.getAuthor_id())
                    .setMsg_author_id_s(accountInfo_vo.getId())
                    .setUnread(1).insert();
        }
        //消息推送到订阅队列[如果推送失败则推送到留言队列]
        Long result=redisUtils.publish(sendMessageFrom.getAuthor_id()+TCPServerConst.CLIENT_SUFFIX,JSON.toJSONString(message_vo));

        //推送到离线队列
        if(!(result>0)){
            redisUtils.listRightPushList(sendMessageFrom.getAuthor_id()+TCPServerConst.CLIENT_OFFLINE_SUFFIX,JSON.toJSONString(message_vo));
        }
        //消息推送到留言队列
        log.info("【pdd博客】消息推送到队列接口:{}",result);
        return ResponseResult.Return(WebResultEmun.SEND_MESSAGE_SUCCESS);
    }

    /**
     * 发送未读消息
     * @param accountInfo_vo
     * @return
     */
    @Override
    public Message_Vo sendUnreadMessage(AccountInfo_Vo accountInfo_vo) {
        //未读消息数量
        Long size=redisUtils.listSize(accountInfo_vo.getId()+TCPServerConst.CLIENT_OFFLINE_SUFFIX);
        if(size!=null&&size>0){
            //取出第一条消息
            String result=redisUtils.listRangeList(accountInfo_vo.getId()+TCPServerConst.CLIENT_OFFLINE_SUFFIX,0L,1L).get(0);
            String JsonObject=new String(result);
            //拿出第一条消息
            Message_Vo message_vo= JSON.parseObject(JsonObject,Message_Vo.class);
            //生成消息准备发送
            return SystemMessageUtil.getUnReadMessage(message_vo.getUser_vo().getId(),size);
        }
        return null;
    }

    /**
     * 查询历史消息记录
     * @param pageIndex
     * @param pageSize
     * @param author_id
     * @return
     */
    @Override
    public ResponseEntity getMessageHistory(Integer pageIndex, Integer pageSize, Integer author_id) {

        AccountInfo_Vo accountInfo_vo=accountUtil.getLoginInfo();

        IPage<Blog_Message> page=blog_messageMapper.selectPage(new Page<>(pageIndex,pageSize),author_id,accountInfo_vo.getId());
        if(pageIndex==1){
            //删除留言队列
            redisUtils.deleteFromRedis(accountInfo_vo.getId()+TCPServerConst.CLIENT_OFFLINE_SUFFIX);
            //将冒泡信息消除
            blog_message_listMapper.update(new Blog_Message_List().setUnread(0),Wrappers.<Blog_Message_List>query()
                    .eq("msg_author_id",accountInfo_vo.getId()).eq("msg_author_id_s",author_id).eq("isdel",0));
        }
        return ResponseResult.Return(page);
    }

    /**
     * 拉取消息列表
     * @return
     */
    @Override
    public ResponseEntity getMessageList() {
        AccountInfo_Vo accountInfo_vo=accountUtil.getLoginInfo();
        if(accountInfo_vo==null){
            return ResponseResult.Return(WebResultEmun.LOGIN_INFO_NOT_EXISTS);
        }
        List<Blog_Message_List> page=blog_message_listMapper.selectList(accountInfo_vo.getId());
        return ResponseResult.Return(page);
    }

    /**
     * 删除聊天窗口
     * @param jsonObject
     * @return
     */
    @Override
    public ResponseEntity delMessageList(JSONObject jsonObject) {
        if(jsonObject==null||jsonObject.getInteger("author_id")==null){
            return  ResponseResult.RETURN_ERROR("author_id不能为空");
        }
        AccountInfo_Vo accountInfo_vo=accountUtil.getLoginInfo();
        if(accountInfo_vo==null){
            return ResponseResult.Return(WebResultEmun.LOGIN_INFO_NOT_EXISTS);
        }
        Blog_Message_List blog_message_list=new Blog_Message_List();
        blog_message_list.setIsdel(1);
        Integer result=blog_message_listMapper.update(blog_message_list,Wrappers.<Blog_Message_List>query().eq("msg_author_id",accountInfo_vo.getId())
                .eq("msg_author_id_s",jsonObject.getInteger("author_id")).eq("isdel",0));
        if(result>0){
            log.info("【pdd博客】删除聊天窗口成功,author_id:{},author_id_s:{}",accountInfo_vo.getId(),jsonObject.getInteger("author_id"));
            return ResponseResult.Return(WebResultEmun.DEL_MESSAGE_LIST_SUCCESS);
        }
        return ResponseResult.Return(WebResultEmun.DEL_MESSAGE_LIST_ERROR);
    }

    /**
     * 创建聊天窗口
     * @param jsonObject
     * @return
     */
    @Override
    public ResponseEntity createMessageBox(JSONObject jsonObject) {
        if(jsonObject==null||jsonObject.getInteger("author_id")==null){
            return  ResponseResult.RETURN_ERROR("author_id不能为空");
        }
        AccountInfo_Vo accountInfo_vo=accountUtil.getLoginInfo();
        if(accountInfo_vo==null){
            return ResponseResult.Return(WebResultEmun.LOGIN_INFO_NOT_EXISTS);
        }
        Blog_Message_List blog_message_list=blog_message_listMapper.selectOne(Wrappers.<Blog_Message_List>query().
                eq("msg_author_id",accountInfo_vo.getId()).eq("msg_author_id_s",jsonObject.getInteger("author_id")).eq("isdel",0));
        if(blog_message_list==null){
            //新增聊天列表记录未读数
            boolean resut=new Blog_Message_List()
                    .setMsg_author_id(accountInfo_vo.getId())
                    .setMsg_author_id_s(jsonObject.getInteger("author_id"))
                    .setUnread(0).insert();
            if(resut){
                return ResponseResult.Return(WebResultEmun.CREATE_MESSAGE_BOX_SUCCESS);
            }else{
                return ResponseResult.Return(WebResultEmun.CREATE_MESSAGE_BOX_ERROR);
            }
        }
        return ResponseResult.Return(WebResultEmun.CREATE_MESSAGE_BOX_SUCCESS);
    }
}
